<?php

defined('IN_PHPCMS') or exit('No permission resources.');
pc_base::load_app_class('foreground');

//会员
class index extends foreground {

    public function __construct() {
        parent::__construct();
    }

    private function _session_start() {
        $session_storage = 'session_' . pc_base::load_config('system', 'session_storage');
        pc_base::load_sys_class($session_storage);
    }

    //首页
    public function init() {
        $info = $this->memberinfo;
        $uid = (int)param::get_cookie('_userid');

        $db_content = pc_base::load_model('content_model');
        $db_collect = pc_base::load_model('collect_model');

        //我的课程
        $db_apply_class = pc_base::load_model('apply_class_model');
        $apply_num = $db_apply_class->count("uid=$uid and a_catid=1");

        //收藏课程
        $like_class_num = $db_collect->count("uid=$uid and a_catid=1");

        //我的关注
        $like_tt = $db_collect->count("uid=$uid and a_catid in (2,10)");

        //播放历史
        $db_view = pc_base::load_model('apply_expert_model');
        $view_num = $db_view->count("uid=$uid", '*');
        

        //订单数
        $this->db_shop = pc_base::load_model('shop_model');
        $shop_num = $this->db_shop->count(['status' => 99]);

        //提醒数
        $db_reminds = pc_base::load_model('reminds_model');
        $reminds_num = $db_reminds->count("uid=" . $uid . " and readed!=1");
        $reminds_num = $reminds_num > 0 ? $reminds_num : '';
        $code = uid2code($info['userid']);
        $d=date('Y-m-d',time());
        $jifen_log = pc_base::load_model('jifen_log_model');
        $r=$jifen_log->get_one('ymd ="'.$d.'" and uid='.$uid.' and content="获得红包"');
        //print_r($r);exit();
        include template('member', 'index');
    }
    public function teacher_apply(){
        include template('member', 'teacher_apply');
    }
    public function do_teachers_apply(){
        $_POST['goodjob']='phpcms';
        $_POST['trade']='it';
        $_POST['realname']='yuan';
        $_POST['mobile']='15921241838';
        $_POST['job']='php';
        $_POST['type']='1,2,0';
        $_POST['num']=2;
        $num=intval($_POST['num']);
        $_POST['con1']='数据测试数据测试数据测试数据测试数据测试数据测试数据测试数据测试数据测试数据测试数据测试数据测试';
        $_POST['con2']='测试数据测试数据测试数据测试数据测试数据测试数据测试数据测试数据测试数据测试数据测试数据测试数据';
        if (!empty($_POST['goodjob']) && isset($_POST['goodjob']) && is_badword($_POST['goodjob']) == false) {
            $goodjob=$_POST['goodjob'];
        } else {
            echo '输入信息不合法！';exit();
        }
        if (!empty($_POST['trade']) && isset($_POST['trade']) && is_badword($_POST['trade']) == false) {
            $trade=$_POST['trade'];
        } else {
            echo '输入信息不合法！';exit();
        }
        if (!empty($_POST['realname']) && isset($_POST['realname']) && is_badword($_POST['realname']) == false) {
            $realname=$_POST['realname'];
        } else {
            echo '输入信息不合法！';exit();
        }
        if (isset($_POST['mobile']) && preg_match("/^1\d{10}$/", $_POST['mobile'])) {
            $mobile = $_POST['mobile'];
        } else {
            echo '请提供正确的手机号码！';exit();
        }
        if (!empty($_POST['job']) && isset($_POST['job']) && is_badword($_POST['job']) == false) {
            $job=$_POST['job'];
        } else {
            echo '输入信息不合法！';exit();
        }
        for ($i=1; $i <=$num ; $i++) { 
            if (!empty($_POST['con'.$i]) && isset($_POST['con'.$i]) && is_badword($_POST['con'.$i]) == false) {
                $cons[]=$_POST['con'.$i];
            } else {
                echo '输入信息不合法！';exit();
            }
        }
        
        if (isset($_POST['type'])) {
            $type =str_replace(' ', '', $_POST['type']);
        } else {
            echo '输入信息不合法！';exit();
        }        
        pc_base::load_sys_class('attachment', '', 0);
        $attachment = new attachment();

        $r = $attachment->upload('img');
        if ($r) {
            $thumb = APP_PATH . 'uploadfile/' . $attachment->uploadedfiles[0]['filepath'];            
        } else{
           $thumb = ''; 
        }
        $user_info = [
            'img' => $thumb,
            'trade' => $trade,
            'realname' => $realname,
            'mobile' => $mobile,
            'job' => $job,
            'goodjob' => $goodjob,
            'ip' => ip(),
            'ymd' => date('Y-m-d',time()),
            'ymdhis' => date('Y-m-d H:i:s',time()),
            'type' => $type,
            'status' => 0,
        ]; 
        
        $apply_teachers = pc_base::load_model('apply_teachers_model');
        $apply_id = $apply_teachers->insert($user_info,true);
        $i_can = pc_base::load_model('i_can_model');
        foreach ($cons as &$v) {
            $can = [
                'con' => $v,
                'p_id' => $apply_id,            
                'ymd' => date('Y-m-d',time()),
                'ymdhis' => date('Y-m-d H:i:s',time()),            
            ];
            $i_can->insert($can,true);
        }
        
        if ($apply_id>0) {
            echo 1;exit();
        }else{
            echo '申请失败';exit();
        }
    }
    //注册
    public function register() {
        header("Cache-control: private");
        $this->_session_start();
        if (isset($_GET['type'])&&!empty($_GET['type'])) {                  
            if (isset($_POST['mobile']) && preg_match("/^1\d{10}$/", $_POST['mobile'])) {
                $mobile = $_POST['mobile'];
            } else {
                echo '请提供正确的手机号码！';exit();
            }
            if (empty($_POST['password'])) {          
                echo '密码不合法！';exit();
            }
            if (isset($_POST['password']) && is_badword($_POST['password']) == false) {
                $password = md5($_POST['password']);
            } else {
                echo '密码不合法！';exit();
            }
            if (isset($_POST['code']) && $_POST['code']== $_SESSION['authnum_session']) {
                $code = $_POST['code'];
            } else {
                echo '验证码错误';exit();
            }
            exit();
        }
        if (!isset($_POST['dosubmit'])) { 
            if (isset($_GET['code']) && is_badword($_GET['code']) == false) {
                $code = $_GET['code'];
            } else {
                $code = '';
            }
            
            include template('member', 'register');
            exit();
        }

        $reg_type = isset($_POST['reg_type']) ? (int)$_POST['reg_type'] : 1;
        if ($reg_type == 1) {
            if (isset($_POST['email']) && is_email($_POST['email'])) {
                $email = $_POST['email'];
            } else {
                error_m('请提供正确的邮箱！', HTTP_REFERER);
            }
            $username = $email;
            $type = 'email';
            $has_sql = "username='$username' or email='$email'";
        } else {
            if (isset($_POST['mobile']) && preg_match("/^1\d{10}$/", $_POST['mobile'])) {
                $mobile = $_POST['mobile'];
            } else {
                error_m('请提供正确的手机号码！', 'goback');
            }
            $username = $mobile;
            $type = 'mobile';
            $has_sql = "username='$username'";
        }

        //密码
        if (empty($_POST['password'])) {          
            error_m('密码不合法！', 'goback');
        }
        if (isset($_POST['password']) && is_badword($_POST['password']) == false) {
            $password = md5($_POST['password']);
        } else {
            error_m('密码不合法！', 'goback');
        }

        //check exist
        $res = $this->db->get_one($has_sql);
        if ($res) {
            error_m('您的号码已被使用', 'goback');
        }

        //check yzm
        $yzm = $_POST['yzm'];
        if ($yzm=='') {
            error_m('验证码错误', 'goback');
        }
        $s_yzm = $_SESSION['yzm'][$type]['verifyt'];
        if ($yzm != $s_yzm) {
            error_m('验证码错误', 'goback');
        } else {
            unset($_SESSION['yzm'][$type]['verifyt']);
        }

        //arr
        $user_info = [
            'username' => $username,
            'nickname' => $username,
            'email' => $email,
            'mobile' => $mobile,
            'password' => $password,
            'regip' => ip(),
            'regdate' => SYS_TIME,
            'lastdate' => SYS_TIME,
            'thumb' => IMG_PATH2 . 'icon/peoBg1.jpg',
            'jifen' => 0,
            'exp' => 0,
        ];

        $uid = $this->db->insert($user_info, 1);
        $db_member = pc_base::load_model('member_model');
        $con="亲，恭喜注册成为高见学社天使用户，一起学，加入高见一族。";
        $cha = $db_member::fxx($uid,$con);
        //加 500 积分
        $db_member = pc_base::load_model('member_model');
        $cha = $db_member::log($uid, 500, $db_member::TYPE_LOGIN_FRIST, '首次登陆 +500', __METHOD__);
        
        $yqm = $_POST['yqm'];
        $f_uid = code2uid($yqm);
        
        if ($f_uid < $uid && $f_uid > 0) {
            $this->db->update(['exp' => 200], ['userid' => $f_uid]);          

            $mobile1 = substr($mobile,0,3);
            $mobile2 = substr($mobile,7);
            $user_mobile=$mobile1.'****'.$mobile2;
            $db_member = pc_base::load_model('member_model');
            $cha = $db_member::log($f_uid, 30, $db_member::TYPE_YP_1, "邀请用户$user_mobile", __METHOD__);
            $cha = $db_member::log($uid, 5, $db_member::TYPE_YP_2, "绑定用户$f_uid", __METHOD__);
        }
          

        success_m('注册成功', 'index.php');
    }
    public function qiang(){
        $uid = (int)param::get_cookie('_userid');
        $category = pc_base::load_model('category_model');
        $jifen_log = pc_base::load_model('jifen_log_model');        
        $d=date('Y-m-d',time()); 
        //print_r($d);exit();
        $r=$jifen_log->get_one('ymd ="'.$d.'" and uid='.$uid.' and content="获得红包"');

        if ($r) {            
            echo 1;exit();
        }
        $all=$category->get_one('catid =7');
        $all=$all['description']; 
        if ($all==0) {
            echo 2;exit();
        }       
        $db_member = pc_base::load_model('member_model');
        $jifen=rand(1,100);
        if ($jifen>=$all) {
            $jifen=$all;
        }
        $all=$all-$jifen;
        $category->update(['description' => $all], ['catid' => 7]);
        $now_jifen=$db_member->get_one('userid ='. $uid);
        $jifens=intval($now_jifen['jifen'])+$jifen;
        $db_member->update(['jifen' => $jifens], ['userid' => $uid]);
        
        $add_jifen_log = [
            'uid' => $uid,
            'price' => $jifen,
            'type' => 7,
            'content' => '获得红包',
            'mca' => 'index::qiang',
            'ip' => ip(),
            'ymd' => date('Y-m-d',time()),
            'ymdhis' => date('Y-m-d H:i:s',time())           
        ];
        $jifen_log->insert($add_jifen_log, 1);
        echo '获得'.$jifen.'学分奖励';exit();
    }
    //修改密码
    public function repwd() {
        header("Cache-control: private");
        $this->_session_start();

        if (!isset($_POST['dosubmit'])) {
            include template('member', 'repwd');
            exit();
        }

        $reg_type = isset($_POST['reg_type']) ? (int)$_POST['reg_type'] : 1;
        if ($reg_type == 1) {
            if (isset($_POST['email']) && is_email($_POST['email'])) {
                $email = $_POST['email'];
            } else {
                error_m('请提供正确的邮箱！', HTTP_REFERER);
            }
            $username = $email;
            $type = 'email';
            $has_sql = "username='$username' or email='$email'";
        } else {
            if (isset($_POST['mobile']) && preg_match("/^1\d{10}$/", $_POST['mobile'])) {
                $mobile = $_POST['mobile'];
            } else {
                error_m('请提供正确的手机号码！', 'goback');
            }
            $username = $mobile;
            $type = 'mobile';
            $has_sql = "username='$username' or mobile=$mobile";
        }

        //密码
        if (isset($_POST['password']) && is_badword($_POST['password']) == false) {
            $password = md5($_POST['password']);
        } else {
            error_m('密码不合法！', 'goback');
        }

        //check yzm
        $yzm = $_POST['yzm'];
        $s_yzm = $_SESSION['yzm'][$type]['verifyt'];
        if ($yzm != $s_yzm) {
            error_m('验证码错误', 'goback');
        } else {
            unset($_SESSION['yzm'][$type]['verifyt']);
        }

        $this->db->update(['password' => $password], [$type => $$type]);

        success_m('密码修改成功', MEMBER_PATH);
    }

    //登录
    public function login() {
        $this->_session_start();

        if (!isset($_POST['dosubmit'])) {
            $forward = isset($_GET['forward']) && trim($_GET['forward']) ? urlencode($_GET['forward']) : '';
            include template('member', 'login');
            exit();
        }

        if (isset($_POST['username'])) {
            $username = trim($_POST['username']);
        } else {
            error_m('请输入帐号', HTTP_REFERER);
        }

        if (isset($_POST['password'])) {
            $password = trim($_POST['password']);
            if (!is_password($password)) {
                error_m('密码不合法', HTTP_REFERER);
            }
        } else {
            error_m('请输入密码', HTTP_REFERER);
        }

        //查询帐号
        $res = $this->db->get_one("email='$username' or username='$username'");
        if (!$res) error_m('用户不存在', HTTP_REFERER);

        //验证用户密码
        $password = md5(trim($password));
        if ($res['password'] != $password) {
            error_m('密码错误', HTTP_REFERER, 3000);
        }

        $userid = $res['userid'];
        $username = $res['username'];
        $nickname = empty($res['nickname']) ? $username : $res['nickname'];

        //更新 lastip lastdate
        $updatearr = array('lastip' => ip(), 'lastdate' => SYS_TIME);
        $this->db->update($updatearr, array('userid' => $userid));

        $cookietime = SYS_TIME + 30 * 24 * 3600;
        $phpcms_auth = sys_auth($userid . "\t" . $password, 'ENCODE', get_auth_key('login'));

        param::set_cookie('auth', $phpcms_auth, $cookietime);
        param::set_cookie('_userid', $userid, $cookietime);
        param::set_cookie('_username', $username, $cookietime);
        param::set_cookie('_nickname', $nickname, $cookietime);

        $forward = isset($_REQUEST['forward']) && !empty($_REQUEST['forward']) ? urldecode($_REQUEST['forward']) : MEMBER_PATH;

        //success_m('登录成功', $forward);
        header('Location:' . $forward);
    }

    //退出
    public function logout() {
        param::set_cookie('auth', '');
        param::set_cookie('_userid', '');
        param::set_cookie('_username', '');
        param::set_cookie('_groupid', '');
        param::set_cookie('_nickname', '');
        param::set_cookie('cookietime', '');

        //success_m('退出成功', MEMBER_PATH);
        header('Location:' . MEMBER_PATH);
    }

    //小窗
    public function mini() {
        $_username = param::get_cookie('_username');
        $_userid = param::get_cookie('_userid');

        include template('member', 'mini');
    }

    public function info() {
        $info = $this->memberinfo;

        include template('member', 'info');
    }

}